const router = require('koa-router')()
const { SuccessModel, ErrorModel } = require('../model/resModel');
const { getPostsList, updatePost, newPost, deletePost } = require('../controller/post');

router.get('/api/posts/', async (ctx, next) => {
  const res = await getPostsList(1, 10);
  ctx.body = new SuccessModel(res, '获取文章列表success！');
  // await ctx.render('index', {
  //   title: 'Hello Koa 2!'
  // })
})

router.post('/api/posts/update', async (ctx, next) => {
  const { postId } = ctx.request.query;
  const body = ctx.request.body;
  body.author= "userId1";

  const res = await updatePost(postId, body);

  if(res.affectedRows) {
    ctx.body = new SuccessModel(true, '更新文章success！');
  }else{
    ctx.body = new ErrorModel(false, '更新文章fail');
  }
})

router.post('/api/posts/new', async (ctx, next) => {
  const body = ctx.request.body;
  body.author= "userId1";
  body.postId = '2';

  const res = await newPost(body);

  if(res.affectedRows) {
    ctx.body = new SuccessModel(true, '新增文章success！');
  }else{
    ctx.body = new ErrorModel(false, '新增文章fail');
  }
})

router.get('/api/posts/delete', async (ctx, next) => {
  const { postId } = ctx.request.query;
  const author= "userId1";

  const res = await deletePost(postId, author);

  if(res.affectedRows) {
    ctx.body = new SuccessModel(true, '删除文章success！');
  }else{
    ctx.body = new ErrorModel(false, '删除文章fail');
  }
})


module.exports = router
